import React, {Component} from 'react';
import {Button, Input, message} from 'antd';
import fetch from 'isomorphic-fetch';
import UserInfoTable from './UserInfoTable';
import ActionDiv from './ActionDiv';
import UserModal from './UserModal';
import * as base from "../../common/BaseUrl";

class UserInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {
                    title: '序号',
                    dataIndex: 'id',
                    key: 'id',
                }, {
                    title: '用户姓名',
                    dataIndex: 'name',
                    key: 'name',
                }, {
                    title: '用户名称',
                    dataIndex: 'userName',
                    key: 'userName',
                }, {
                    title: '联系方式',
                    dataIndex: 'telephone',
                    key: 'telephone',
                }, {
                    title: '性别',
                    dataIndex: 'sexName',
                    key: 'sexName',
                }, {
                    title: '年龄',
                    dataIndex: 'age',
                    key: 'age',
                }, {
                    title: 'Action',
                    key: 'action',
                    render: (text, record) => (
                        <span>
                            <Button style={{marginRight: '20px'}} onClick={() => this.goUserUpdateModal(event, record)}
                                    size="small">修改</Button>
                            <Button onClick={() => this.reset(event, record)} size="small">重置密码</Button>
                        </span>
                    ),
                }],
            dataSource: [],
            pagination: {},
            pageSize: 10,
            searchName: '',
            visible: false,
            selectedRowKeys: [],
            defaultValue: {},
            action: '',
            title: '',
            newRandomKey: 1
        };
        this.refresh = this.refresh.bind(this);
        this.saveUserInfo = this.saveUserInfo.bind(this);
        this.goAddModal = this.goAddModal.bind(this);
        this.goUserUpdateModal = this.goUserUpdateModal.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.deleteUserInfo = this.deleteUserInfo.bind(this);
        this.handleTableChange = this.handleTableChange.bind(this);
        this.onChangeSearchName = this.onChangeSearchName.bind(this);
        this.onSelectChange = this.onSelectChange.bind(this);
        this.saveFormRef = this.saveFormRef.bind(this);
        this.reset = this.reset.bind(this);
        this.showMessage = this.showMessage.bind(this);
    }

    componentDidMount() {
        this.refresh();
    }

    refresh() {
        let userName = this.state.searchName;
        let pageSize = this.state.pageSize;
        let url = base.BaseUrl + "react/userInfo/selectUserInfo";
        let formData = new FormData();
        formData.append("userName", userName);
        formData.append("pageSize", pageSize);
        formData.append("pageNum", 1);
        fetch(url, {
            method: 'post',
            body: formData,
            header: base.headers,
            credentials: 'include',
            redirect: 'follow',
            mode: 'cors'
        }).then(res => res.json()).then(json => {
            let total = json.total;
            //如果这边不定义会怎么样
            let pagination = this.state.pagination;
            pagination.total = total;
            pagination.current = json.pageNumber;
            let userInfoList = json.userInfoList;
            this.setState({
                dataSource: userInfoList,
                pagination: pagination
            });
        }).catch(err => {
            console.log(err);
        })
    }

    goAddModal() {
        let defaultValue = {name: '', userName: '', password: '', telephone: '', sex: '1', age: ''};
        this.setState({
            visible: !this.state.visible,
            defaultValue: defaultValue,
            action: 'save',
            title: '新增人员信息',
            newRandomKey: this.state.newRandomKey + 1
        });
    }

    saveUserInfo(action) {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            let url;
            let formData = new FormData();
            if (action === 'update') {
                url = base.BaseUrl + "react/userInfo/updateUserInfo";
                let id = this.state.defaultValue.id;
                console.log(id);
                formData.append('id', id);
            } else {
                url = base.BaseUrl + "react/userInfo/saveUserInfo";
            }
            formData.append("name", values.name);
            formData.append("userName", values.userName);
            formData.append("password", values.password);
            formData.append("telephone", values.telephone);
            formData.append("sex", values.sex);
            formData.append("age", values.age);
            fetch(url, {
                method: 'post',
                body: formData,
                header: base.headers,
                credentials: 'include',
                redirect: 'follow',
                mode: 'cors'
            }).then(res => res.json()).then(json => {
                let messageType = 'error';
                let message = '保存失败';
                if (json) {
                    this.refresh();
                    form.resetFields();
                    this.setState({visible: false});
                    messageType = 'success';
                    message = '保存成功';
                }
                this.showMessage(messageType, message, 8);
            });
        });
    }

    goUserUpdateModal(event, record) {
        event.preventDefault();
        this.setState({
            visible: !this.state.visible,
            defaultValue: record,
            action: 'update',
            title: '修改人员信息',
            newRandomKey: this.state.newRandomKey + 1
        });
    }

    showMessage(type, message, time) {
        if (type == 'error') {
            message.error(message, time);
        } else {
            message.success(message, time);
        }
    }

    reset(event, record) {
        event.preventDefault();
        let id = record.id;
        let formData = new FormData();
        formData.append("id", id);
        let url = base.BaseUrl + "/react/userInfo/resetPassword";
        fetch(url, {
            method: 'post',
            body: formData,
            header: base.headers,
            credentials: 'include',
            redirect: 'follow',
            mode: 'cors'
        }).then(res => res.json()).then(json => {
            let messageType = 'error';
            let message = '密码重置失败';
            if (json) {
                record.password = "123";
                messageType = 'success';
                message = '密码重置成功'
            }
            this.showMessage(messageType, message, 5);
        })
    }

    handleCancel() {
        this.setState({
            visible: !this.state.visible
        });
    }

    onSelectChange(selectedRowKeys) {
        this.setState({selectedRowKeys: selectedRowKeys});
    }

    deleteUserInfo() {
        let selectedRowKeys = this.state.selectedRowKeys;
        let url = base.BaseUrl + 'react/userInfo/deleteUserInfo';
        let formData = new FormData();
        formData.append("selectedRowKeys", selectedRowKeys);
        fetch(url, {
            method: 'post',
            body: formData,
            header: base.headers,
            credentials: 'include',
            redirect: 'follow',
            mode: 'cors'
        }).then(res => res.json()).then(json => {
            let messageType = 'error';
            let message = '用户删除失败';
            if (json) {
                this.refresh();
                messageType = 'success';
                message = '用户删除成功';
            }
            this.showMessage(messageType, message, 5);
        });
    }

    onChangeSearchName(e) {
        this.setState({
            searchName: e.target.value
        });
    }

    handleTableChange(pagination, filters, sorter) {
        let userName = '';
        const pager = this.state.pagination;
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        let formData = new FormData();
        formData.append("userName", userName);
        formData.append("pageSize", this.state.pageSize);
        formData.append("pageNumber", pager.current);
        this.constructorGameTable(formData);
    }

    saveFormRef(form) {
        this.form = form;
    }

    render() {
        let selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <div>
                <Input placeholder="input search text" style={{width: 200}} onChange={this.onChangeSearchName}/>
                <ActionDiv refresh={this.refresh} deleteInfo={this.deleteUserInfo}
                           goAddModal={this.goAddModal}/>
                <UserInfoTable columns={this.state.columns} dataSource={this.state.dataSource}
                               pagination={this.state.pagination} onChange={this.handleTableChange}
                               rowSelection={rowSelection}/>
                <UserModal newRandomKey={this.state.newRandomKey} visible={this.state.visible}
                           saveUserInfo={this.saveUserInfo} title={this.state.title}
                           handleCancel={this.handleCancel} saveFormRef={this.saveFormRef}
                           defaultValue={this.state.defaultValue} action={this.state.action}/>
            </div>
        );
    }
}

export default UserInfo;